/**
  * @FileName: CountDownButton.java
  * @Package:com.bdtop.dbl.ui.widgets
  * @Description: TODO
  * @author: MingjunLi
  * @date:2014-9-23
  * @version V1.0
  */
package com.bdtop.dbl.ui.view;

import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bdtop.dbl.R;

/**
 * @ClassName: CountDownButton
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-23
 */
public class CountDownButton extends RelativeLayout {
    
    private ButtonTimer mButtonTimer;
    private Button mButton;
    private TextView mTimerView;

    /**
      * @param context
      */
    public CountDownButton(Context context) {
        super(context);
        init();
    }

    /**
     * @param context
     * @param attrs
     */
    public CountDownButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    
    /**
      * @param context
      * @param attrs
      * @param defStyle
      */
    public CountDownButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }
    
    private void init() {
        LayoutInflater.from(getContext()).inflate(R.layout.count_down_btn, this);
        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                if (mButtonTimer != null) {
                    mButtonTimer.onFinish();
                }
            }
        });
        
        mTimerView = (TextView) findViewById(R.id.timer);
    }

    private class ButtonTimer extends CountDownTimer {

        /**
          * @param millisInFuture
          * @param countDownInterval
          */
        public ButtonTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            if (mButtonTimer != null) {
                mButtonTimer.cancel();
                mButtonTimer = null;
            }
            CountDownButton.this.performClick();
        }

        @Override
        public void onTick(long millisUntilFinished) {
            long second = millisUntilFinished / 1000;
            mTimerView.setText(second + "s");
        }
    }
    
    public void start(long countDownTime, long countDownInterval) {
        mButtonTimer = new ButtonTimer(countDownTime, countDownInterval);
        mButtonTimer.start();
    }
}
